package cn.wen.base.view.banner;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.LinearInterpolator;

import java.lang.ref.WeakReference;
import java.lang.reflect.Field;

import cn.wen.base.adapter.viewpager.QuickPagerAdapter;


/**
 * 轮播图的ViewPager
 */

public class BannerViewPager extends ViewPager implements View.OnTouchListener {
    private QuickPagerAdapter mAdapter;
    private MyHandler mHandler;
    private static final int ROLL_MSG = 0x0011;// 轮播消息What
    private long mRollTime = 4500;// 轮播的时间
    private Activity mActivity;// 当前View的Activity
    private boolean isLoop = true;
    private BannerScroller mBannerScroller;
    private int downX;
    private OnRightListener onRightListener;
    /**
     * Activity的生命周期监听回调
     */
    private DefActivityLifecycleCallbacks mCallbacks;

    public BannerViewPager(Context context) {
        this(context, null);
    }

    public BannerViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        try {
            // 选用反射来改变滚动的速度
            Field mScroller = ViewPager.class.getDeclaredField("mScroller");
            mBannerScroller = new BannerScroller(context, new LinearInterpolator());
            mScroller.setAccessible(true);
            mScroller.set(this, mBannerScroller);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (getContext() instanceof Activity) {
            mActivity = (Activity) getContext();
        }
        // 设置触摸监听
        setOnTouchListener(this);
        mHandler = new MyHandler(this);
    }


    /**
     * 设置Banner的adapter
     *
     * @param adapter
     */
    public void setAdapter(QuickPagerAdapter adapter) {
        mAdapter = adapter;
        // 调用父类的
        super.setAdapter(adapter);
    }

    /**
     * 注册Activity的生命周期监听
     */
    private void addActivityCallBack() {
        if (mActivity != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                if (mCallbacks == null) {
                    mCallbacks = new DefActivityLifecycleCallbacks() {
                        @Override
                        public void onActivityResumed(Activity activity) {
                            if (activity == mActivity) {
                                startRoll();
                            }
                        }

                        @Override
                        public void onActivityPaused(Activity activity) {
                            if (mHandler == null) {
                                return;
                            }
                            if (activity == mActivity) {
                                mHandler.removeMessages(ROLL_MSG);
                            }

                        }

                        @Override
                        public void onActivityDestroyed(Activity activity) {
                            if (activity == mActivity) {
                                removeActivityCallback();
                                mActivity = null;
                                mCallbacks = null;
                            }


                        }
                    };
                }
                mActivity.getApplication().registerActivityLifecycleCallbacks(mCallbacks);

            }
        }
    }

    /**
     * 移除Activity的生命周期监听
     */
    private void removeActivityCallback() {
        try {
            if (mHandler != null) {
                mHandler.removeCallbacksAndMessages(null);
            }
            // 移除Activity的生命周期监听
            if (mActivity != null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                    mActivity.getApplication().unregisterActivityLifecycleCallbacks(mCallbacks);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onAttachedToWindow() {
        // 注册Activity的生命周期监听
        addActivityCallBack();
        super.onAttachedToWindow();
    }

    /**
     * 销毁Handler
     */
    @Override
    protected void onDetachedFromWindow() {
        removeActivityCallback();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        super.onDetachedFromWindow();
    }

    /**
     * 开启自动轮播
     */
    public void startRoll() {
        if (mHandler == null) {
            return;
        }
        // 清除消息
        mHandler.removeMessages(ROLL_MSG);
        if (isLoop) {
            mHandler.sendEmptyMessageDelayed(ROLL_MSG, mRollTime);
        }
    }

    /**
     * 处理一些错误
     */
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        try {
            return super.onInterceptTouchEvent(ev);
        } catch (IllegalArgumentException e) {
        } catch (ArrayIndexOutOfBoundsException e) {
        }
        return false;
    }

    int moveX;

    /**
     * 兼容低版本
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
            getParent().requestDisallowInterceptTouchEvent(true);
        }
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downX = (int) ev.getX();
                moveX = (int) ev.getX();
                //当前viewpager对应的夫控件不能去拦截事件
                getParent().requestDisallowInterceptTouchEvent(false);
                break;
            case MotionEvent.ACTION_MOVE:
                moveX = (int) ev.getX();

                break;
            case MotionEvent.ACTION_UP:
                int diff = moveX - downX;
                if (!isLoop && diff < -100 && mAdapter != null && getCurrentItem() == mAdapter.getDataSize() - 1) {
                    //夫控件拦截事件
                    getParent().requestDisallowInterceptTouchEvent(true);
                    return false;
                }
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (mHandler != null) {
                    // 停止轮播
                    mHandler.removeMessages(ROLL_MSG);
                }
                break;
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
                // 清除消息
                startRoll();
                break;
        }
        return false;
    }

    /**
     * 设置滚动的时间
     */
    public void setRollTime(long rollTime) {
        this.mRollTime = rollTime;
    }

    /**
     * 设置是否轮播
     *
     * @param isLoop
     */
    public void setLoop(boolean isLoop) {
        this.isLoop = isLoop;
        if (mAdapter != null) {
            mAdapter.setLoop(isLoop);
        }
        if (!isLoop && mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    /**
     * ViewPager划动速度时间
     */
    public void setDuration(int duration) {
        if (mBannerScroller != null) {
            mBannerScroller.setDuration(duration);
        }
    }

    public interface OnRightListener {
        void onRight();
    }

    public void setOnRightListener(OnRightListener onRightListener) {
        this.onRightListener = onRightListener;
    }

    //CT
    private static class MyHandler extends Handler {
        WeakReference<BannerViewPager> bannerViewPagerWeakReference;

        MyHandler(BannerViewPager bannerViewPager) {
            bannerViewPagerWeakReference = new WeakReference<>(bannerViewPager);
        }

        @Override
        public void handleMessage(Message ms) {
            BannerViewPager bannerViewPager = bannerViewPagerWeakReference.get();
            if (bannerViewPager != null) {
                // 切换到下一页
                bannerViewPager.setCurrentItem(bannerViewPager.getCurrentItem() + 1);
                // 不断的轮播
                bannerViewPager.startRoll();
            }
        }
    }
}
